package net.dntuan.training.mvc.security.authentication;

import java.util.ArrayList;

import java.util.List;

import net.dntuan.training.mvc.security.Role;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

@Component("simpleAuthenticationProvider")
public class SimpleAuthenticationProvider implements AuthenticationProvider {

    private static final Logger LOGGER = LoggerFactory.getLogger(SimpleAuthenticationProvider.class);

    public SimpleAuthenticationProvider() {
        LOGGER.debug("initialize bean");
    }

    // TODO how many times is this method called?
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();
        LOGGER.debug("entered username: " + username);

        Authentication auth = null;
        if (username.equalsIgnoreCase("super") && password.equalsIgnoreCase("super")) {
            List<GrantedAuthority> roles = new ArrayList<GrantedAuthority>();
            roles.add(Role.USER);
            roles.add(Role.ADMIN);
            User user = new User("super", "super", true, true, true, true, roles);
            // TODO User contains authorities information too. So if a custom
            // Authentication is used, it should use DbUser instead of
            // userdetails.User
            auth = new UsernamePasswordAuthenticationToken(user, null, roles);

        } else if (username.equals("denied")) {
            // TODO throw BadCredentialsException with message key 'custom_key'.
            // declare message bundle in spring.xml
        }
        return auth;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        LOGGER.debug("Type of Authentication instance: " + authentication.getCanonicalName());
        // TODO what to implement?
        return true;
    }

}
